<?php
if (!defined('_PS_VERSION_'))
	exit;

class RateComments extends Module
{
	const INSTALL_SQL_FILE = 'install.sql';

	private $_html = '';
	
	public function __construct()
	{
		$this->name = 'ratecomments';
		$this->tab = 'front_office_features';
		$this->version = '2.1';
		$this->author = 'nguyentn';
		$this->need_instance = 0;

		parent::__construct();

		$this->displayName = $this->l('Product Comments & Rating');
		$this->description = $this->l('Allow users to post comment about a product.');
	}

	public function install()
	{
		if (!file_exists(dirname(__FILE__).'/'.self::INSTALL_SQL_FILE))
			return false;
		elseif (!$sql = file_get_contents(dirname(__FILE__).'/'.self::INSTALL_SQL_FILE))
			return false;
		$sql = str_replace(array('PREFIX_', 'ENGINE_TYPE'), array(_DB_PREFIX_, _MYSQL_ENGINE_), $sql);		
		$sql = preg_split("/;\s*[\r\n]+/", trim($sql));

		foreach ($sql AS $query)
			if (!Db::getInstance()->Execute(trim($query)))
				return false;
		if (parent::install() == false OR $this->registerHook('extraright') == false OR $this->registerHook('header') == false)
			return false;
		return true;
	}
	
	function uninstall()
	{
		if (!parent::uninstall())
			return false;
		return true;
	}
	
	protected function _postProcess()
	{		
		global $currentIndex;
		if (Tools::isSubmit('active'))
		{
			Db::getInstance()->Execute('
			UPDATE `'._DB_PREFIX_.'product_ratecomment` SET
			`active` = '.(int)(Tools::getValue('active')).'
			WHERE `id_product_ratecomment` = '.(int)(Tools::getValue('id')));
			
			Tools::redirectAdmin($currentIndex.'&configure='.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules'));
		}
		elseif(Tools::isSubmit('delete'))
		{
			Db::getInstance()->Execute('
			DELETE FROM `'._DB_PREFIX_.'product_ratecomment` 
			WHERE `id_product_ratecomment` = '.(int)(Tools::getValue('id')));
			
			Tools::redirectAdmin($currentIndex.'&configure='.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules'));
		}
		elseif(Tools::isSubmit('activeAll'))
		{
			foreach(Tools::getValue('selected_comment') as $value){
				Db::getInstance()->Execute('
				UPDATE `'._DB_PREFIX_.'product_ratecomment` SET
				`active` = 1
				WHERE `id_product_ratecomment` = '.(int)($value));
				
			}
		}
		elseif(Tools::isSubmit('deactiveAll'))
		{
			foreach(Tools::getValue('selected_comment') as $value){
				Db::getInstance()->Execute('
				UPDATE `'._DB_PREFIX_.'product_ratecomment` SET
				`active` = 0
				WHERE `id_product_ratecomment` = '.(int)($value));
				
			}
		}
		elseif(Tools::isSubmit('deleteAll'))
		{
			foreach(Tools::getValue('selected_comment') as $value){
				Db::getInstance()->Execute('
				DELETE FROM `'._DB_PREFIX_.'product_ratecomment` 
				WHERE `id_product_ratecomment` = '.(int)($value));
			}
		}
	}
	
	public function getContent()
	{
		$this->_postProcess();
		return $this->_displayForm();
	}
	
	private function _displayForm()
	{
		global $currentIndex, $cookie;
		$data = $this->_getData();
		$this->_html = '<h2>'.$this->displayName.'</h2>';
		$this->_html .= '<fieldset class="width2">
			<legend>'.$this->l('List Comment').'</legend>';
		$this->_html.= '
			<form action="'.Tools::safeOutput($_SERVER['REQUEST_URI']).'" method="post">
			<table class="table">
				<thead>
					<tr>
						<th style="width:260px;"></th>
						<th style="width:260px;">'.$this->l('Customer').'</th>
						<th style="width:260px;">'.$this->l('Content').'</th>
						<th style="width:260px;">'.$this->l('Date').'</th>
						<th style="width:260px;">'.$this->l('Status').'</th>
						<th style="width:30px;">'.$this->l('Actions').'</th>
					</tr>
					</thead>
					<tbody>';
		
		foreach ($data AS $item)
		{
			$this->_html .= '
					<tr>
						<td><input type="checkbox" value="'.$item['id_product_ratecomment'].'" name="selected_comment[]" /></td>
						<td>'.$item['customer_name'].'</td>
						<td>'.$item['content'].'</td>
						<td>'.Tools::displayDate($item['date_add']).'</td>
						<td>'.($item['active']==1? $this->l('accept') : $this->l('no accept')).'</td>
						<td>
							<a href="'.$currentIndex.'&configure='.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules').($item['active']==1? '&active=0':'&active=1').'&id='.(int)($item['id_product_ratecomment']).'"><img src="'.$this->_path.'img/accept.png" alt="'.$this->l('Accept').'" title="'.$this->l('Accept').'" /></a>
							<a href="'.$currentIndex.'&configure='.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules').'&delete=1'.'&id='.(int)($item['id_product_ratecomment']).'""><img src="'.$this->_path.'img/delete.png" alt="'.$this->l('Delete').'" title="'.$this->l('Delete').'" /></a>
						</td>
					<tr>';
		}
		$this->_html .= '</tbody></table>
		<p>&nbsp;</p>
		<input type="submit" name="activeAll" value="'.$this->l('Active Selected').'" class="button" />
		<input type="submit" name="deactiveAll" value="'.$this->l('Deactive Selected').'" class="button" />
		<input type="submit" name="deleteAll" value="'.$this->l('Delete Selected').'" class="button" />
			
		</form>';
		$this->_html .= '</fieldset>';
		return $this->_html;
	}
	
	private function _frontOfficePostProcess()
	{
		global $smarty, $cookie, $errors;
		require_once(dirname(__FILE__).'/ProductCommentRate.php');
		
		if (Tools::isSubmit('submitMessage') AND empty($cookie->id_customer) === false)
		{
			$customerComment = ProductCommentRate::getByCustomer((int)(Tools::getValue('id_product')), (int)$cookie->id_customer);
			if ((strtotime($customerComment['date_add']) + Configuration::get('PRODUCT_COMMENTS_MINIMAL_TIME')) < time())
			{
				$comment = new ProductCommentRate();
				$comment->content = strip_tags(Tools::getValue('content'));
				$comment->id_product = (int)$_GET['id_product'];
				$comment->id_customer = (int)$cookie->id_customer;
				$comment->grade = (int)Tools::getValue('grade');
				$comment->active = 0;
				if (!$comment->content)
					$errors[] = $this->l('Invalid comment text posted.');
				else
				{
					if (!$comment->save())
						$errors[] = $this->l('An error occurred while saving your comment.');
					else
						$smarty->assign('confirmation', $this->l('Cám ơn bạn đã bình luận.').((int)(Configuration::get('PRODUCT_COMMENTS_MODERATE')) ? ' '.$this->l('Awaiting moderator validation.') : ''));
				}
			}
			else
				$errors[] = $this->l('You should wait').' '.Configuration::get('PRODUCT_COMMENTS_MINIMAL_TIME').' '.$this->l('seconds before posting a new comment');
		}
		
	}

	public function hookExtraRight($params)
	{
		
		global $smarty, $cookie;
		$nbComment = $this->_getData((int)Tools::getValue('id_product'),true);
		$listComment = $this->_getData((int)Tools::getValue('id_product'),false, false, true);
		$smarty->assign(array(
			'logged' => (int)$cookie->id_customer,
			'product_comment_path' => $this->_path,
			'listComment' => $listComment
		));

		$controller = new FrontController();
		$controller->pagination((int)$nbComment);
		
		return ($this->display(__FILE__, '/ratecomments.tpl'));
	}
	public function hookHeader()
	{
		Tools::addCSS($this->_path.'css/ratecomments.css');
		$this->_frontOfficePostProcess();
	}
	
	private function _getData($id_product=0,$count=false,$limit=false,$active=false)
	{
		if($count)
		{
			$sql = 'SELECT COUNT(id_product_ratecomment) AS `total` FROM '._DB_PREFIX_.'product_ratecomment WHERE active=1';
			$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql);
			return isset($result) ? $result['total'] : 0;
		}
		$p = Tools::getValue('p',1);
		$n = Tools::getValue('n',4);
		
		$sql = "SELECT prc.*, CONCAT(firstname,' ',lastname) as customer_name
				FROM "._DB_PREFIX_."product_ratecomment prc
				LEFT JOIN "._DB_PREFIX_."customer c ON prc.id_customer=c.id_customer 
				WHERE 1=1 AND grade<>0 "
				.($id_product!=0? ' AND prc.id_product = '.$id_product : '') 		
				.($active? ' AND prc.active=1' : '') 
				.($limit? ' LIMIT '.(((int)($p) - 1) * (int)($n)).','.(int)($n) : '');
		
		
		
		return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
	}
}
